package com.monitor.action;

import java.io.PrintWriter;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;

import com.google.gson.Gson;
import com.monitor.po.Administrator;
import com.monitor.util.Constants;
import com.opensymphony.xwork2.ActionSupport;

public class MonitorActionSupport extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware, ServletContextAware {

	/**
	 * 序列號
	 */
	private static final long serialVersionUID = 7346958706279798803L;
	protected static final String CONTENT_TYPE = "text/html; charset=utf-8";
	public static final String FILE_SAVE_DIR = "file.saveDir";
	public static final String FILE_CONFIG_NAME = "fileupload";

	// 請求
	protected HttpServletRequest request;
	// 响应
	protected HttpServletResponse response;
	// 会话
	protected Map<String, Object> session;

	protected ServletContext mContext;

	/**
	 * @return the session
	 */
	public Map<String, Object> getSession() {
		return session;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	@Override
	public void setServletContext(ServletContext context) {
		mContext = context;
	}

	protected boolean isAdmin() {
		Object sessionObj = session.get(Constants.SESSION_USER);
		if (sessionObj != null) {
			if (sessionObj instanceof Administrator) {
				return true;
			}
		}
		return false;
	}

	protected boolean isLogined() {
		Object sessionUser = session.get(Constants.SESSION_USER);
		if (sessionUser != null && (sessionUser instanceof Administrator)) {
			return true;
		}
		return false;
	}

	protected PrintWriter getWriter() throws Exception {
		response.setContentType(CONTENT_TYPE);
		PrintWriter out = response.getWriter();
		return out;
	}

	protected void printJSONString(Object obj) throws Exception {
		PrintWriter out = getWriter();
		Gson gson = new Gson();
		out.print(gson.toJson(obj));
		out.flush();
		out.close();
	}

	/**
	 * 获取上传文件的目录
	 * 
	 * @return
	 */
	protected String getSaveDirName() {
		// 获取文件配置
		ResourceBundle rb = ResourceBundle.getBundle(FILE_CONFIG_NAME);
		// 获取文件上传保存路径配置
		return rb.getString(FILE_SAVE_DIR);
	}

}
